package com.bsh.controller;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsh.api.ApiUtils;
import com.bsh.api.params.DtoWeiXinSign;
import com.bsh.mybatis.model.User;
import com.bsh.mybatis.model.WxRecomend;
import com.bsh.repository.DaoWxRec;
import com.bsh.service.UserService;
import com.bsh.utils.HttpClientUtils;

@Controller
public class WeiXinSignController {
	private static Logger log = LoggerFactory
			.getLogger(WeiXinSignController.class);

	@Autowired
	DaoWxRec wxRecomend;
	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;	
	@Autowired
	HttpSession session;
	@Autowired
	UserService servUser;
	
	private static String appId = "wx37dc608022d668fc";
	private static String secret = "09689b0395ade8809c92587e64062b17";
	String code;
	String openId = "";
	String unionId = "";
	String lang = "zh_CN";
	String mobile = "";
	
	@RequestMapping(value = "/api/registerWeiXin",method=RequestMethod.GET)
	@ResponseBody
	public ModelAndView init(HttpServletRequest _request,HttpServletResponse _response) throws Exception{
		log.info("进入微信weixinsignInit::start");
		session.setAttribute("goTo","");
		this.request=_request;
		this.response=_response;
		this.code = request.getParameter("code");
		this.unionId = "";
		String ua = request.getHeader("user-agent").toLowerCase();
		String referer = request.getHeader("referer");
		String state = request.getParameter("state");
		this.mobile = "";
		if(!ApiUtils.objIsEmpty( request.getParameter("mobile") )){
			this.mobile = request.getParameter("mobile");
		}else if(!ApiUtils.objIsEmpty( request.getParameter("user") )){
			//为兼容之前老版本的分享传url为user
			this.mobile = request.getParameter("user");
		}
        if (ua.indexOf("micromessenger") > 0 && this.mobile != "") {// 是微信浏览器
        	        	
        	if(ApiUtils.objIsEmpty(this.code) && ( ApiUtils.objIsEmpty(referer) || referer.indexOf("open.weixin.qq.com") <=0 ) ){
        	    String formUrl = URLEncoder.encode(request.getRequestURL().toString()+ "?" + (request.getQueryString()) );
        	    log.info("weixinsignInit::"+formUrl);
        	    String gotoUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+formUrl+"&response_type=code&scope=snsapi_userinfo&state=wxReg#wechat_redirect";
//        	    response.sendRedirect(gotoUrl);
        	    session.setAttribute("goTo", gotoUrl);
        	    return null;
        	}
			
			if(!ApiUtils.objIsEmpty(code) && !ApiUtils.objIsEmpty(state) && state.equals("wxReg")){
				bulid();
			}
			
        }
//        session.setAttribute("wxUnionId", 123);
        session.setAttribute("wxUnionId", this.unionId);
		return null;
	}
	
	protected void bulid() throws Exception{
		DtoWeiXinSign reqTwo = stepB(this.code);
		DtoWeiXinSign reqD = stepD(reqTwo.getAccessToken(), reqTwo.getOpenId(), this.lang);
		if(!ApiUtils.objIsEmpty(reqD.getOpenId())){
			log.info("weixin:先查数据库");
			WxRecomend recordCheck = new WxRecomend();
			recordCheck.setUnionid(reqD.getUnionid());
			recordCheck.setpMobile(this.mobile);
			WxRecomend selectRes = wxRecomend.selectByUnionId(recordCheck);
			if(selectRes != null && selectRes.getUnionid().equals(reqD.getUnionid())){
				log.info("weixinSign::数据库已经存在 ");
				return;
			}
			User userWx = servUser.getUserByMobile(this.mobile);
			if(ApiUtils.objIsEmpty(userWx)){
				log.info("weixinSign::查不到手机号的用户"+this.mobile);
				return;
			}
			if(!userWx.getLevel().equals("vip") && !userWx.getLevel().equals("gold")){
				log.info("weixinSign::只有vip 和金钻才有推荐和锁粉");
				return;    //只有vip 和金钻才有推荐和锁粉
			}
			log.info("weixinSign::进入数据库插入");
			//插入数据库
			WxRecomend record = new WxRecomend();
			record.setpMobile(this.mobile);
			record.setOpenid(reqD.getOpenId());
			record.setNickname(reqD.getNickName());
			record.setSex(reqD.getSex().toString());
			record.setProvince(reqD.getProvince());
			record.setCity(reqD.getCity());
			record.setCountry(reqD.getCountry());
			record.setHeadImgUrl(reqD.getHeadimgUrl());
			record.setUnionid(reqD.getUnionid());
			record.setCreateTime(new Date());
			int intoRes = wxRecomend.insert(record);
			log.info("weixinSign::数据库操作状态为("+intoRes+")");
			
		}else{
			log.error("weixinSign:bulidStepD error ,get openid error,不进入数据库相关操作");
		}
	}

	public String getOpenId(){
		return this.openId;
	}
	public String getUnionId(){
		return this.unionId;
	}
	/**
	 * 微信认证第二步
	 * 返回结果对象内的 accessToken，用于下一步使用
	 * 
	 * @param code
	 * @param state
	 * @return accessToken
	 * @throws Exception 
	 */
	protected DtoWeiXinSign stepB(String code) throws Exception{
		//处理第二步
		//redirect_uri/?code=CODE&state=STATE。
		DtoWeiXinSign res = new DtoWeiXinSign();
		if(code == null || code == ""){
			res.setError("error");
			log.error("weixin stepB: error CodeIsNull");
			return res;
		}
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
		log.info("weixinSign::stepB url "+url);
        String result = HttpClientUtils.executeGet(url);
		JSONObject rq = (JSONObject) JSON.parse(result);
		if(!ApiUtils.objIsEmpty(rq)){
			log.info("weixinSign:stepB result>"+rq);
			if(!ApiUtils.objIsEmpty(rq.get("errcode"))){
				//返回错误信息
				log.error("WeixinSign_stepTwo::errcode"+rq.get("errcode")+" errmsg:"+rq.get("errmsg"));
			}
			
			if(!ApiUtils.objIsEmpty(rq.getString("access_token"))){
				String accessToken = rq.getString("access_token");
				String openId = rq.getString("openid");
				DtoWeiXinSign req = new DtoWeiXinSign();
				req.setAccessToken(accessToken);
				req.setOpenId(openId);
				req.setRefreshToken(rq.getString("refresh_token"));
				log.info("wexinSign_stepTwo:: token:"+accessToken+" openId:"+openId);
				return req;
			}else{
				//微信请求返回的access_token错误
				log.error("WeixinSign_stepTwo::getAccessToken error!");
			}
			
		}else{
			//微信请求失败，没有返回结果
			log.error("WeixinSign_stepTwo::getResult is null!");
		}

		return res;
	}
	
	protected DtoWeiXinSign stepD(String accessToken, String openId, String lang) throws Exception{
		//处理第四步
		this.unionId = "";
		//redirect_uri/?code=CODE&state=STATE。
		DtoWeiXinSign res = new DtoWeiXinSign();
		if(accessToken == null || accessToken == "" || openId == null || openId == ""){
			res.setError("error");
			log.info("weixinSign: stepD,ERROR token:"+accessToken+" openId:"+openId+" lang:"+lang);
			return res;
		}
		if(lang == null || lang == ""){
			lang = this.lang;
		}
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openId+"&lang="+lang;
		log.info("weixinSign: stepD url>"+url);
        String result = HttpClientUtils.executeGet(url);
		JSONObject rq = (JSONObject) JSON.parse(result);
		if(!ApiUtils.objIsEmpty(rq)){
			log.info("weixinSign: stepD result>"+rq);
			if(!ApiUtils.objIsEmpty(rq.get("errcode"))){
				//返回错误信息
				log.error("WeixinSign_stepD::errcode"+rq.get("errcode")+" errmsg:"+rq.get("errmsg"));
			}
			
			if(!ApiUtils.objIsEmpty(rq.getString("openid"))){
				
				res.setOpenId(rq.getString("openid"));
				res.setNickName(rq.getString("nickname"));
				res.setSex(rq.getIntValue("sex"));
				res.setProvince(rq.getString("province"));
				res.setCity(rq.getString("city"));
				res.setCountry(rq.getString("country"));
				res.setHeadimgUrl(rq.getString("headimgurl"));
				res.setPrivilege(rq.getString("privilege"));
				res.setUnionid(rq.getString("unionid"));
				this.unionId = rq.getString("unionid");
				res.setError("success");
				return res;
			}else{
				//微信请求返回的access_token错误
				log.error("WeixinSign_stepD::getopenid error!");
			}
			
		}else{
			//微信请求失败，没有返回结果
			log.error("WeixinSign_stepD::getResult is null!");
		}

		return res;
	}
	
	
}
